﻿#include "http.h"

Http::Http()
{
}

int Http::protocolParaInit(void* para_struct)
{
    HttppParaTypeDef* m_http_para = (HttppParaTypeDef*)para_struct;
    QUrl url(m_http_para->url_str);
    if (!url.isValid()) {
        qDebug() << "URL is not valid";
        return -1;
    }

    if (!url.isRelative()) {
        qDebug() << "URL is not a relative path";
        return -2;
    }

    m_url = url;
    return 0;
}

int Http::protocolOpen()
{
    return 0;
}

int Http::protocolWrite(const QByteArray& data_buf)
{
    if (m_request == nullptr) {
        m_request = new QNetworkRequest();

        m_request->setUrl(m_url);
        m_request->setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));
    }

    if (m_manager == nullptr) {
        m_manager = new QNetworkAccessManager(this);
    }
    connect(m_manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply) {
        QString loginResultJson;
        QByteArray buf_byte_array = reply->readAll();
        qDebug() << buf_byte_array;

        char char_buf[buf_byte_array.size()];
        memcpy(char_buf, buf_byte_array, buf_byte_array.size());

        this->receiveDataCallback(char_buf);

        // 获取http状态码
        QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        if (statusCode.isValid()) {
            qDebug() << "status code=" << statusCode.toInt();
        }

        QNetworkReply::NetworkError err = reply->error();
        if (err != QNetworkReply::NoError) {
            qDebug() << "Failed: " << reply->errorString();
            return -1;
        } else {
            // 获取返回内容
            qDebug() << "loginResultJson  is  " << QString::fromStdString(buf_byte_array.toStdString());
            loginResultJson = QString::fromStdString(buf_byte_array.toStdString());
            //处理返回数据
        }
        m_manager->deleteLater();
        m_manager = nullptr;
        return 0;
    });

    this->m_manager->post(*m_request, data_buf);

    return 0;
}

int Http::protocolClose()
{
    if (this->m_manager != nullptr) {
        m_manager->deleteLater();
        m_manager = nullptr;
    }

    if (this->m_request != nullptr) {
        delete m_request;
        m_request = nullptr;
    }

    return 0;
}

void Http::setProtocolReadCallbackFunc(ReceiveDataCallback callBackFunc)
{
    this->receiveDataCallback = callBackFunc;
}

Http::~Http()
{
    m_manager->deleteLater();
    m_manager = nullptr;

    delete m_request;
    m_request = nullptr;
}
